package com.smarttiger.zero.admin.service;

import com.smarttiger.zero.admin.dao.DataSourceDao;
import com.smarttiger.zero.admin.entity.DataSourceModel;
import com.smarttiger.zero.admin.util.Constant;
import com.smarttiger.zero.admin.util.Message;
import com.smarttiger.zero.admin.util.ParamNames;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class DataSourceService extends BaseService<DataSourceModel> {
    @Autowired
    DataSourceDao dao;

    @PostConstruct
    public void initMethod() {
        super.setDao(dao);
    }

    @ParamNames("name,page")
    public Message getDataSource(String name,String page) {
        Message message = new Message();
        Pageable pageable = PageRequest.of(Integer.valueOf(page).intValue(), Constant.PAGESIZE, Sort.by(Sort.Direction.DESC,"createDate"));
        Page<DataSourceModel> all = dao.findAll(new Specification<DataSourceModel>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<DataSourceModel> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(name)) {
                    predicates.add(criteriaBuilder.like(root.get("name"), name + "%"));
                }
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createDate")));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        },pageable);
        long totalElements = all.getTotalElements();
        message.setData(all.getContent());
        message.setTotal((int)totalElements);
        return message;
    }
}
